﻿using ITSM.Model;
using ITSM.Model.Model;
using ITSM.Service;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Data;
using System.Reflection;

namespace ITSM.Controllers.DemandConfirmation
{
    [Route("api/[controller]")]
    [ApiController]
    public class DemandConfirmationController : ControllerBase
    {

        private readonly IDemand _demand;
        private readonly IUserInfo _userInfo;
        public DemandConfirmationController(IDemand demand, IUserInfo userInfo)
        {
            _demand = demand;
            _userInfo = userInfo;
        }

        // GET api/<DemandConfirmation>/5
        [HttpPost]
        public IActionResult PostDCList(M_DemandList demand)
        {
            if (string.IsNullOrWhiteSpace(demand.RYD_Company))
            {
                return NotFound();
            }
            if (demand.Page <= 0)
            {
                return NotFound();
            }
            var data = _demand.DemandList(demand);
            return Ok(data);
        }

        // GET api/<DemandConfirmation>/5
        [HttpPost("/api/DemandConfirmationExcel")]
        public IActionResult DemandConfirmationExcel(M_DemandList demand)
        {
            if (string.IsNullOrWhiteSpace(demand.RYD_Company))
            {
                return NotFound();
            }
            if (demand.Page <= 0)
            {
                return NotFound();
            }
            var list = _demand.DemandList(demand).DemandList;
            list.ForEach(res =>
            {
                switch (res.RYD_Level)
                {
                    case 1:
                        res.RYD_LevelName = "一般";
                        break;
                    case 2:
                        res.RYD_LevelName = "紧急";
                        break;
                    case 3:
                        res.RYD_LevelName = "严重";
                        break;
                    case 4:
                        res.RYD_LevelName = "重大";
                        break;
                    default:
                        break;
                }
                switch (res.RYD_State)
                {
                    case 1:
                        res.RYD_StateName = "待接单";
                        break;
                    case 2:
                        res.RYD_StateName = "已接单";
                        break;
                    case 3:
                        res.RYD_StateName = "已完成";
                        break;
                    case 4:
                        res.RYD_StateName = "已评价";
                        break;
                    default:
                        break;
                }
                if (!string.IsNullOrWhiteSpace(res.RYD_ToItId))
                {
                    res.RYD_ToItId = _userInfo.QueryUserInfo(res.RYD_ToItId).RYD_Name;
                }
            });
            DataTable dataTable = ToDataTable(list); // 此处准备 dataTable 数据
            for (int i = dataTable.Columns.Count - 1; i >= 0; i--)
            {
                switch (dataTable.Columns[i].ColumnName)
                {
                    case "RYD_DemandTypeName":
                        dataTable.Columns[i].ColumnName = "类别名称";
                        break;
                    case "RYD_Name":
                        dataTable.Columns[i].ColumnName = "IT负责人";
                        break;
                    case "RYD_Phone":
                        dataTable.Columns[i].ColumnName = "IT负责人联系方式";
                        break;
                    case "RYD_Id":
                        dataTable.Columns.RemoveAt(i);
                        break;
                    case "RYD_Company":
                        dataTable.Columns[i].ColumnName = "所在公司";
                        dataTable.Columns[i].SetOrdinal(0);
                        dataTable.Columns.RemoveAt(i);
                        break;
                    case "RYD_DemandId":
                        dataTable.Columns[i].ColumnName = "订单单号";
                        break;
                    case "RYD_UserId":
                        dataTable.Columns.RemoveAt(i);
                        break;
                    case "RYD_Level":
                        dataTable.Columns[i].ColumnName = "紧急级别";
                        break;
                    case "RYD_State":
                        dataTable.Columns[i].ColumnName = "订单状态";
                        break;
                    case "RYD_TypeId":
                        dataTable.Columns.RemoveAt(i);
                        break;
                    case "RYD_ItId":
                        dataTable.Columns.RemoveAt(i);
                        break;
                    case "RYD_ToItId":
                        dataTable.Columns[i].ColumnName = "是否转单";
                        break;
                    case "RYD_UserStartTime":
                        dataTable.Columns[i].ColumnName = "用户发起需求时间";
                        break;
                    case "RYD_ItStartTime":
                        dataTable.Columns[i].ColumnName = "IT接单时间";
                        break;
                    case "RYD_ItEndTime":
                        dataTable.Columns[i].ColumnName = "IT完单时间";
                        break;
                    case "RYD_UserEndTime":
                        dataTable.Columns[i].ColumnName = "用户确认完成时间";
                        break;
                    case "RYD_DemandDetails":
                        dataTable.Columns[i].ColumnName = "需求详情";
                        break;
                    case "RYD_Files":
                        dataTable.Columns.RemoveAt(i);
                        break;
                    case "RYD_UserName":
                        dataTable.Columns[i].ColumnName = "发起人姓名";
                        break;
                    case "RYD_UserPhone":
                        dataTable.Columns[i].ColumnName = "发起人联系方式";
                        break;
                    case "RYD_UserAddress":
                        dataTable.Columns[i].ColumnName = "发起人地址";
                        break;
                    case "RYD_UserIp":
                        dataTable.Columns[i].ColumnName = "发起人IP地址";
                        break;
                    case "RYD_Reason":
                        dataTable.Columns[i].ColumnName = "问题原因";
                        break;
                    case "RYD_Solution":
                        dataTable.Columns[i].ColumnName = "解决方案";
                        break;
                    case "RYD_Star":
                        dataTable.Columns[i].ColumnName = "评价星级";
                        break;
                    case "RYD_Evaluate":
                        dataTable.Columns[i].ColumnName = "评价内容";
                        break;
                    case "RYD_KBId":
                        dataTable.Columns[i].ColumnName = "知识库编号";
                        break;
                    case "RYD_CreateTime":
                        dataTable.Columns.RemoveAt(i);
                        break;
                    case "RYD_CreateBy":
                        dataTable.Columns.RemoveAt(i);
                        break;
                    case "RYD_ModifyTime":
                        dataTable.Columns.RemoveAt(i);
                        break;
                    case "RYD_ModifyBy":
                        dataTable.Columns.RemoveAt(i);
                        break;
                    default:
                        break;
                }
            }
            string name = "ITSM需求记录";
            ExcelUtil excelUtil = new ExcelUtil();
            byte[] bytes = excelUtil.DataTableToExcel(dataTable, name);
            return File(bytes, "application/octet-stream", $"{name}_{DateTime.Now:yyyyMMddHHmmssfff}.xlsx");
        }


        /**/
        /// <summary>
        /// 将泛型集合类转换成DataTable
        /// </summary>
        /// <typeparam name="T">集合项类型</typeparam>
        /// <param name="list">集合</param>
        /// <returns>数据集(表)</returns>
        public static DataTable ToDataTable<T>(List<T> list)
        {
            return ListToDataTable<T>(list);
        }

        /// <summary>
        /// 将泛类型集合List类转换成DataTable
        /// </summary>
        /// <param name="list">泛类型集合</param>
        /// <returns></returns>
        public static DataTable ListToDataTable<T>(List<T> entitys)
        {
            try
            {
                //检查实体集合不能为空
                if (entitys == null )
                {
                    return new DataTable();
                    //throw new Exception("需转换的集合为空");
                }
                if(entitys.Count < 1)
                {
                    return new DataTable();
                }
                //取出第一个实体的所有Propertie
                //Type entityType = entitys[0].GetType();
#pragma warning disable CS8602 // 解引用可能出现空引用。
                PropertyInfo[] entityProperties = entitys[0].GetType().GetProperties();
#pragma warning restore CS8602 // 解引用可能出现空引用。

                //生成DataTable的structure
                //生产代码中，应将生成的DataTable结构Cache起来，此处略
                DataTable dt = new("temp");
                for (int i = 0; i < entityProperties.Length; i++)
                {
                    //dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType);
                    dt.Columns.Add(entityProperties[i].Name);
                }
                //将所有entity添加到DataTable中
#pragma warning disable CS8600 // 将 null 字面量或可能为 null 的值转换为非 null 类型。
                foreach (object entity in entitys)
                {
                    //检查所有的的实体都为同一类型
                    //if (entity.GetType() != entityType)
                    //{
                    //    throw new Exception("要转换的集合元素类型不一致");
                    //}
                    object[] entityValues = new object[entityProperties.Length];
                    for (int i = 0; i < entityProperties.Length; i++)
                    {
#pragma warning disable CS8601 // 引用类型赋值可能为 null。
                        entityValues[i] = entityProperties[i].GetValue(entity, null);
#pragma warning restore CS8601 // 引用类型赋值可能为 null。
                    }
                    dt.Rows.Add(entityValues);
                }
#pragma warning restore CS8600 // 将 null 字面量或可能为 null 的值转换为非 null 类型。
                return dt;
            }
            catch (Exception)
            {
                return new DataTable();
                throw;
            }
        }
    }
}
